<template>
  <view class="parking-page">
    <!-- 搜索栏 -->
    <uni-search-bar 
      placeholder="搜索停车场" 
      radius="100"
      @confirm="searchParking"
    />

    <!-- 模式切换 -->
    <view class="mode-switch">
      <button 
        :class="['switch-btn', viewMode === 'list' ? 'active' : '']"
        @click="switchMode('list')"
      >列表</button>
      <button 
        :class="['switch-btn', viewMode === 'map' ? 'active' : '']"
        @click="switchMode('map')"
      >地图</button>
    </view>

    <!-- 列表模式 -->
    <view v-if="viewMode === 'list'" class="list-container">
      <uni-list>
        <uni-list-item 
          v-for="item in parkingList"
          :key="item.id"
          :title="item.name"
          :note="item.address"
          :rightText="item.distance + 'km'"
        >
          <template v-slot:footer>
            <text class="price">¥{{ item.price }}/小时</text>
          </template>
        </uni-list-item>
      </uni-list>
    </view>

    <!-- 地图模式 -->
    <map 
      v-else
      id="parkingMap"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :polyline="polyline"
      class="map-container"
      show-location
    />
  </view>
</template>

<script>
export default {
  data() {
    return {
      viewMode: 'list',
      latitude: 39.90469,
      longitude: 116.40717,
      markers: [],
      polyline: [],
      parkingList: [
        {
          id: 1,
          name: '中关村停车场',
          address: '北京市海淀区中关村大街1号',
          distance: 0.8,
          price: 15,
          latitude: 39.90469,
          longitude: 116.40717
        }
      ]
    }
  },
  methods: {
    searchParking(value) {
      console.log('搜索关键词:', value)
    },
    switchMode(mode) {
      this.viewMode = mode
      if (mode === 'map') this.initMap()
    },
    async initMap() {
      try {
        const res = await this.getLocation()
        this.latitude = res.latitude
        this.longitude = res.longitude
        this.markers = this.parkingList.map(item => ({
          id: item.id,
          latitude: item.latitude,
          longitude: item.longitude,
          title: item.name,
          iconPath: '/static/marker.png',
          width: 30,
          height: 30
        }))
      } catch (err) {
        uni.showToast({ title: '获取位置失败', icon: 'none' })
      }
    },
    getLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          success: resolve,
          fail: reject
        })
      })
    }
  }
}
</script>